
require 'debugout'


class ComponentManager
  def initialize(parameter)
    component_dir = parameter.get("component_manager.dir")
    @components = {}

    # add special components
    add_component(:compoent_manager, self)
    add_component(:parameter, parameter)

    # add other components
    _self = self
    Module.new do |mod|
      Dir.glob(component_dir + "/*.rb") do |file|
        mod.module_eval(open(file).read)
      end
      mod.constants.each do |cls_name|
        cls = mod.const_get(cls_name)
        if cls.const_defined?(:COMPONENT_NAME) then
          comp_name = cls.const_get(:COMPONENT_NAME)
          _self.add_component(comp_name, cls.new)
        end
      end
    end

    @components.each do |name, comp|
      Debugout.puts Debugout::LEVEL_DEBUG, "init component '#{name}'"
      comp.init_as_component(self)
    end
  end

  def init_as_component(component_manager)
  end

  def component(comp_name)
    return @components[comp_name]
  end

  def call_func(comp_name, func_name, args)
    comp = @components[comp_name]
    comp.send(func_name, *args)
  end

  def add_component(comp_name, obj)
    @components[comp_name] = obj
  end

end
